<?php
namespace app\service;

use think\Service;
use EasyWeChat\MiniApp\Application;
use Qcloud\Cos\Client as Cos;
// Download：https://github.com/aliyun/openapi-sdk-php
// Usage：https://github.com/aliyun/openapi-sdk-php/blob/master/README.md

class Weapp extends Service
{
    private $handle;
    private $sesskey;
    public $openid;

    public $message = '';
    public $state = 200;

    public function __construct(){
        $this->handle = new Application(config('wechat.mini'));
        // $this->handle['guzzle_handler'] = SwooleHandler::class;
        session('?sesskey') && ($this->sesskey = session('sesskey'));
        session('?openid') && ($this->openid = session('openid'));
        // $response = $app->server->serve();
        
        // 将响应输出
        // $response->send();exit; // Laravel 里请使用：return $response;
    }
    /*
     * 登录授权
     */
    public function auth(string $code){
        $session = $this->handle->getUtils()->codeToSession($code);
        session('sesskey', $session['session_key']);
        session('openid', $session['openid']);
        $this->sesskey = $session['session_key'];
        $this->openid = $session['openid'];
        return $session;
    }
    /*
     * 解密
     */
    public function decrypt(string $iv, string $encryptedData){
        return $this->handle->getUtils()->decryptSession($this->sesskey, $iv, $encryptedData);
    }
    /*
     * 模板消息(统一服务消息,通过公众号发送)
     */
    public function send(string $openid, string $tmpl_id, string $path = 'index', array $data=[]){
        $send = [
            'touser' => $openid,  // 用户wechat_openid
            'mp_template_msg' => [
                'appid' => config('weixin.app_id'),
                'template_id' => $tmpl_id, // 模板ID
                'url' => $path, // 跳转路径
                'miniprogram' => [
                    'appid' => config('weapp.app_id'),
                    'pagepath' => $path,
                ],
                'data' => $data
            ]
        ];
        return $this->handle->uniform_message->send($send);
    }
    /**
     * 小程序码
     *
     * @param string $path
     * @param string $scene
     * @param string $content
     * @param array $options
     * @return void
     */ 
    public function qr(string $path, string $scene, string $content, array $options = []){
        $resp = $this->handle->app_code->getUnlimit($scene, array_merge(['page' => 'pages/' . $path], $options));
        if ($resp instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $cos = new Cos(config('cos.'));
            $params = [
                'Bucket' => config('cos.bucket'),
                'Key' => 'plan/qocode-' . $id . '.jpg',
                'Body' => $content
            ];
            $result = $cos->putObject($params);
        }
    }
    /**
     * 订阅消息
     *
     * @param string $template_id
     * @param string $touser
     * @param int $page
     * @param array $params
     * @return void
     */
    public function subscribe(string $template_id, string $touser, int $page, array $params = []){
        $data = [
            'template_id' => $template_id, // 所需下发的订阅模板id
            'touser' => $touser,     // 接收者（用户）的 openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => []
        ];
        foreach($params as $key => $val){
            $data['data'][$key] = ['value' => $val];
        }
        return $this->handle->subscribe_message->send($data);    
    }
}
